from sqlalchemy.ext.asyncio import create_async_engine
from sqlalchemy.ext.asyncio import async_sessionmaker
from urllib.parse import quote_plus
from server.settings import Settings

secondary_db_username = Settings.database_settings.secondary_db_username
secondary_db_password = Settings.database_settings.secondary_db_password
secondary_db_host = Settings.database_settings.secondary_db_host
secondary_db_port = Settings.database_settings.secondary_db_port
secondary_db_database = Settings.database_settings.secondary_db_database
secondary_db_protocol = 'mysql+asyncmy'

if Settings.database_settings.secondary_db_type == 'postgresql':
    secondary_db_protocol = 'postgresql+asyncpg'


SECONDARY_ASYNC_SQLALCHEMY_DATABASE_URL = (
    f'{secondary_db_protocol}://{secondary_db_username}:{quote_plus(secondary_db_password)}@'
    f'{secondary_db_host}:{secondary_db_port}/{secondary_db_database}'
)

secondary_async_engine = create_async_engine(
    SECONDARY_ASYNC_SQLALCHEMY_DATABASE_URL,
    echo=Settings.database_settings.secondary_db_echo,
    max_overflow=Settings.database_settings.secondary_db_max_overflow,
    pool_size=Settings.database_settings.secondary_db_pool_size,
    pool_recycle=Settings.database_settings.secondary_db_pool_recycle,
    pool_timeout=Settings.database_settings.secondary_db_pool_timeout,
)

SecondaryAsyncSessionLocal = async_sessionmaker(autocommit=False, autoflush=False, bind=secondary_async_engine)